package com.example.exp2019_4;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.Image;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

public class MyOnTouch implements View.OnTouchListener {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int eventaction = event.getAction();

        ImageView imageView = v.findViewById(R.id.test);
        switch (eventaction) {
            case MotionEvent.ACTION_DOWN:
                int[] location = new int[2];
                int[] location1 = new int[2];

                imageView.getLocationOnScreen(location);
                location1[0] = (int)event.getRawX();
                location1[1] = (int)event.getRawY();
                location1[0] = (int)event.getRawX() - location[0];
                location1[1] = (int)event.getRawY() - location[1];
                //移动动画
                TranslateAnimation animation = new TranslateAnimation(0,location1[0],0,location1[1]);

				//设置动画显示时间
				animation.setDuration(3000);
				animation.setFillAfter(true);
				imageView.startAnimation(animation);

				//获取Frame动画并显示：实现移动过程中的眨眼/咧嘴动作
                final AnimationDrawable frameAnimation=(AnimationDrawable) imageView.getBackground();
                if (frameAnimation.isRunning()) //如果正在播放,则先停止
                    frameAnimation.stop();
                frameAnimation.start(); //开始播放动画

        }
        return false;
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @param
     *            （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}
